package demo

import (
	"errors"
	"fmt"
	"reflect"
)

func IteratorFields(val any) {
	res, err := iteratorFields(val)

	if err != nil {
		fmt.Println(err)
		return
	}

	for k, v := range res {
		fmt.Println(k, v)
	}
}

func iteratorFields(val any) (map[string]any, error) {
	if val == nil {
		return nil, errors.New("不能为 nil")
	}

	typ := reflect.TypeOf(val)
	refVal := reflect.ValueOf(val)
	fmt.Println("xxxxxxxxxxxxxxxxxxx:", typ.Name())
	for typ.Kind() == reflect.Pointer {
		typ = typ.Elem()
		refVal = refVal.Elem()
	}

	numFiled := typ.NumField()
	res := make(map[string]any, numFiled)

	for i := 0; i < numFiled; i++ {
		fdType := typ.Field(i).Name
		res[fdType] = refVal.Field(i).Interface()
	}

	return res, nil
}
